package org.aom.litebean.module.menu;

import java.util.Map;

import org.aom.entity.menu.Module;
import org.aom.entity.menu.ModuleItem;
import org.aom.litebean.module.base.BaseBean;
import org.aom.service.menu.IModuleItemManager;
import org.aom.service.menu.IModuleManager;
import org.aom.util.FaceUtil;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.ManagedProperty;
import org.operamasks.faces.annotation.Required;
import org.operamasks.faces.annotation.SaveState;
import org.operamasks.faces.component.grid.impl.UIEditDataGrid;
import org.operamasks.faces.component.grid.provider.GridDataProvider;
import org.operamasks.faces.util.Browser;

@ManagedBean(name = "module.menu.moduleItemManageBean", scope = ManagedBeanScope.REQUEST)
public class ModuleItemManageBean extends BaseBean {

	// 父模块属性
	@Bind(id = "moduleName", attribute = "value")
	@Required(message = "#{this.getMessages().get('required')}")
	private String moduleName;

	// 常量
	public static String SELECTED_MODULE_ID = "selectedModuleId";
	public static String ACTION_NAME = "action";

	// 传过来的属性
	@SaveState
	private Long selectedModuleId;

	@SaveState
	private Module selectedModule = null;

	// 页面中的临时变量，以便于EditGrid的实体操作
	@Bind(id = "moduleItemDataGrid", attribute = "addedData")
	private Object addedData;
	@Bind(id = "moduleItemDataGrid", attribute = "modifiedData")
	private Object modifiedData;
	@Bind(id = "moduleItemDataGrid", attribute = "removedData")
	private Object removedData;
	@SuppressWarnings("unused")
	@Bind(id = "moduleItemDataGrid", attribute = "bindBean")
	private String bindBean = "org.aom.entity.menu.ModuleItem";

	// 涉及到父子模块的服务层
	@ManagedProperty("#{moduleManager}")
	private IModuleManager moduleManager;

	@ManagedProperty("#{moduleItemManager}")
	private IModuleItemManager moduleItemManager;

	@Bind(id = "moduleItemDataGrid", attribute = "idColumn")
	private static String idColumn = "id";

	@Bind(id = "moduleItemDataGrid", attribute = "binding")
	private UIEditDataGrid moduleItemDataGrid;

	@SuppressWarnings( { "unused", "serial" })
	@Bind(id = "moduleItemDataGrid", attribute = "dataProvider")
	private GridDataProvider getDataProvider() {
		Map<String, Object> session = FaceUtil.getSessionMap();
		if (session.get(ACTION_NAME).toString().equals("mod")) {
			selectedModuleId = (Long) session.get(SELECTED_MODULE_ID);
			selectedModule = moduleManager.get(selectedModuleId);
		}
		return new GridDataProvider() {

			@Override
			public Object[] getElements() {
				if (selectedModule != null) {
					return moduleItemManager.pageQueryByModule(start, limit,
							idColumn, true, selectedModule).toArray();
				} else
					return null;
			}

			@Override
			public int getTotalCount() {
				if (selectedModule != null) {
					return moduleItemManager.totlaNumByModule(selectedModule);
				} else
					return 0;
			}

			public Object[] getElementsById(String[] ids) {
				return moduleItemManager.getElementsById(ids).toArray();
			}
		};
	}

	/**
	 * 绑定添加按钮的点击击事件
	 */
	@Action(id = "add")
	public void add() {
		moduleItemDataGrid.insertRow(0);
	}

	/**
	 * 绑定删除按钮的点击事件
	 */
	@Action(id = "del")
	public void del() {
		moduleItemDataGrid.remove();
	}

	/**
	 * 绑定mod取消按钮的点击事件，使用immediate=true跳过数据验证
	 */
	@Action(id = "cancel_main", immediate = true)
	public void cancel_main() {
		moduleName = "";
		// 主模块的dataGrid刷新
		Browser.execClientScript("window.parent.BtnJsvar.fireEvent('click');");
	}

	@Action(id = "ok")
	public void ok() {
		remove();
		Map<String, Object> session = FaceUtil.getSessionMap();
		if (session.get(ACTION_NAME).toString().equals("add")) {
			save();
		} else {
			modify(session);
		}
		moduleItemDataGrid.commit();
		moduleItemDataGrid.reload();
		cancel_main();

	}

	/**
	 * 如果完全是新增模块只走save方法
	 */
	private void save() {
		Module newModule = new Module();
		newModule.setName(moduleName);
		moduleManager.save(newModule);
		if (addedData != null) {
			ModuleItem[] moduleItem = (ModuleItem[]) addedData;
			for (ModuleItem addData : moduleItem) {
				ModuleItem newItem = new ModuleItem();
				newItem.setIcon(addData.getIcon());
				newItem.setName(addData.getName());
				newItem.setUrl(addData.getUrl());
				newItem.setModule(newModule);
				moduleItemManager.save(newItem);
			}
		}
	}

	/**
	 * 如果只是编辑模块
	 * 
	 * @param session
	 */
	private void modify(Map<String, Object> session) {
		selectedModuleId = (Long) session.get(SELECTED_MODULE_ID);
		Module selectedModule = moduleManager.get(selectedModuleId);
		// 修改子模块信息
		if (modifiedData != null) {
			ModuleItem[] moduleItem = (ModuleItem[]) modifiedData;
			for (ModuleItem newData : moduleItem) {
				ModuleItem data = moduleItemManager.get(newData.getId());
				data.setIcon(newData.getIcon());
				data.setName(newData.getName());
				data.setUrl(newData.getUrl());
				moduleItemManager.save(data);
			}
		}
		// 新增子模块
		if (addedData != null) {
			ModuleItem[] moduleItem = (ModuleItem[]) addedData;
			for (ModuleItem addData : moduleItem) {
				ModuleItem newData = new ModuleItem();
				newData.setIcon(addData.getIcon());
				newData.setName(addData.getName());
				newData.setUrl(addData.getUrl());
				newData.setModule(selectedModule);
				moduleItemManager.save(newData);
			}
		}
	}

	// 删除子模块信息
	private void remove() {
		if (removedData != null) {
			ModuleItem[] moduleItem = (ModuleItem[]) removedData;
			for (ModuleItem removeData : moduleItem) {
				moduleItemManager.delete(removeData.getId());
			}
		}
	}

	@BeforeRender
	protected void beforeRender(boolean isPostBack) {
		initBaseResource();
		Map<String, Object> session = FaceUtil.getSessionMap();
		if (session.get(ACTION_NAME).toString().equals("mod")) {
			selectedModuleId = (Long) session.get(SELECTED_MODULE_ID);
			selectedModule = moduleManager.get(selectedModuleId);
			moduleName = selectedModule.getName();
		}
	}
}
